/**
* @Title: caseAuditList_Ctrl.js
* @Description: TODO
* Copyright: Copyright (c) 2014 
 * Company:中国平安
*
* @Project HIMS-FWA
* @date 2014年10月27日 下午4:43:38
* @version V1.0
*/
;
(function(){
	'use strict';
	
	var app = angular.module('fwa.mainApp');
	app.controller('CaseAuditAddCtrl', ['$scope', '$http','$state','$location','$stateParams','$modal','WarningScreenService',
                	'CaseAuditAddService','WarningAddService','BaseURL','Modal','AuditDictServices','CaseCommonService',
                	function ($scope,$http,$state,$location,$stateParams,$modal,WarningScreenService,
                			caseAuditAddService,WarningAddService,baseUrl,Modal,AuditDictServices,CaseCommonService){
		
		$scope.auditDictServices = AuditDictServices;
		AuditDictServices.initCodeListDatas();
		$scope.caseAuditAddService = caseAuditAddService;
		$scope.caseMedicalData = {};
		
		var goBackUrl ="";
		
		var codeType=['COMPLAIN_TYPE','SOURCE_TYPE'];
		$scope.staffCount= 0;
		$scope.insurCount= 0;
		$scope.medicalCount= 0;
		
		
		
		$scope.initInsuranceData=[];
		$scope.initStaffData = [];
		$scope.initMedicalData = [];
		$scope.sourceTypeList=[];
		$scope.targetTypeList=[{codeNo:"01",codeName:"医疗机构"},
		                       {codeNo:"02",codeName:"医护人员"},
		                       {codeNo:"03",codeName:"参保人员"}];
        $scope.auditFrom={};
		$scope.queryDetail = function queryDetail(params){
			caseAuditAddService.queryCaseAuditDetail(params).success(function(data){
				var obj = data.result;
				$scope.auditFrom = obj;
				
				
				$scope.auditFrom.periodDate={start:obj.periodBeginDate,end:obj.periodEndDate};
				if(data.opinion){
					$scope.auditFrom.dealUserName = data.opinion.dealUserName;
					$scope.auditFrom.dealDate = data.opinion.dealDate;
					$scope.auditFrom.opinion = data.opinion.opinion;
					$scope.auditFrom.opinionDesc = data.opinion.opinionDesc;
					$scope.auditFrom.opinionDesc = data.opinion.opinionDesc;
				}
			});
		}
		
		$scope.backAudit = function(){
		   	WarningAddService.warningMarks = WarningAddService.warningMarkTemps;//初始化扣分参数
			if(!angular.isUndefined($stateParams.view)){
				if($stateParams.view == 0){
					$state.go("problemRegister.problemRegisterList");					
				}else if($stateParams.view == 1){
					$state.go("problemSearch");					
				}
				
			} else{
				$state.go("problemRegister.problemRegisterList");
			}
		}
   	 	$scope.loading = false;
		$scope.saveAudit = function(dataStatus){
			var dateReg =/^\d{4}-\d{2}-\d{2}$/; 
			if(angular.isUndefined($scope.auditFrom)){
				Modal.alert("请填录入完整事件信息!");
				return;
			}
			if(!$scope.auditFrom.periodDate 
					||  !dateReg.test($scope.auditFrom.periodDate.start)
					|| !dateReg.test($scope.auditFrom.periodDate.end)){
				Modal.alert("请填事件时段,并且必须输入正确的日期格式(yyyy-MM-dd)!");
				return;
			}
			if(!dateReg.test($scope.auditFrom.hearDate)){
				Modal.alert("请填受理时间,并且必须输入正确的日期格式(yyyy-MM-dd)!");
				return;
			}
			if(!$scope.auditFrom.sourceType){
				Modal.alert("请选择来源方式!");
				return;
			}
			if(!$scope.auditFrom.keyPoint){
				Modal.alert("请填写事件要点!");
				return;
			}
			if(!$scope.auditFrom.detailDesc){
				Modal.alert("请填写详细情况!");
				return;
			}
			if($scope.initMedicalData.length ==0){
				Modal.alert("请填写医疗机构信息!");
				return;
			}
			if(angular.isUndefined($scope.auditFrom.opinion) || $scope.auditFrom.opinion == null){
				Modal.alert("请选择处理意见!");
				return;
			}
			if(angular.isUndefined($scope.auditFrom.opinionDesc) || $scope.auditFrom.opinionDesc== null
				|| $scope.auditFrom.opinionDesc== "" ){
				Modal.alert("请填写意见说明!");
				return;
			}
			
			/*if($scope.auditFrom.contactPhone){
				 var filter  = /(^(0[0-9]{2,3}\-)?([2-9][0-9]{4,7})+(\-[0-9]{1,4})?$)|(^((\(\d{3}\))|(\d{3}\-))?(1[3578]\d{9})$)/;
				 if (!filter.test($scope.auditFrom.contactPhone)) {
						Modal.alert('您输入的联系电话值不正确');
						return;
				 }
			}*/
			
			if($scope.auditFrom.contactMail) {
				 var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
				 if (!filter.test($scope.auditFrom.contactMail)) {
					Modal.alert('您输入的电子邮件格式不正确');
					return;
				 }
			}
			var tmpArray = [];
			/**
			 * flag:1 新增
			 * **/
			
			// =========   组装机构数据  ====================
			var orgData = $scope.initMedicalData;
			var _isNum = 0;
			for(var i3=0;i3<orgData.length;i3++){
				var _obj = orgData[i3];
				var _t = new Object();
				if(_obj.isDeleted == 1){
					_isNum++;
				}
				_t.targetCode = _obj.medicalCode;
				_t.flag = _obj.flag;
				_t.targetType = 1;
				_t.taskType = 1;
				_t.isDeleted = _obj.isDeleted;
				tmpArray.push(_t);
			}
			if(_isNum == orgData.length){
				Modal.alert("请填写医疗机构信息!");
				return;
			}
			
			// =========   组装医护人员数据  ====================
			if($scope.initStaffData.length > 0){
				var staffData = $scope.initStaffData;
				_isNum = 0;
				for(var i2=0;i2<staffData.length;i2++){
					var _obj = staffData[i2];
					var _t = new Object();
					if(_obj.isDeleted == 1){
						_isNum++;
					}
					_t.targetCode = _obj.staffCode;
					_t.flag = _obj.flag;
					_t.targetType = 2;
					_t.taskType = 1;
					_t.isDeleted = _obj.isDeleted;
					tmpArray.push(_t);
				}
			}
			
			// =========   组装参保人员数据  ====================
			if($scope.initInsuranceData.length > 0) {
				var isData = $scope.initInsuranceData;
				_isNum = 0;
				for(var i=0;i<isData.length;i++){
					var _obj = isData[i];
					var _t = new Object();
					if(_obj.isDeleted == 1){
						_isNum++;
					}
					_t.targetCode = _obj.insuranceNo;
					_t.flag = _obj.flag;
					_t.targetType = 3;
					_t.taskType = 1;
					_t.isDeleted = _obj.isDeleted;
					tmpArray.push(_t);
				}
			}
			
			var param = $scope.auditFrom;
			param.auditTargetDTO = tmpArray;
			if($scope.auditFrom.periodDate){
				var _pdate = $scope.auditFrom.periodDate;
				param.periodBeginDate = _pdate.start;
				param.periodEndDate = _pdate.end;
			}
			param.problemStatus = dataStatus;//录入时进行初审，事件状态变更为3
			if(dataStatus == 0){
				param.tempFlag = 1;//				
			}else{
				param.tempFlag = 0;//				
			}
			$scope.loading = !$scope.loading;
            param.warnMarkTempDetails=WarningAddService.warningMarks;
			// 医疗机构
			var rob = caseAuditAddService.saveCaseAudit(param,function(data){
				$scope.loading = !$scope.loading;
				$scope.auditFrom.auditProblemId = data.auditProblemId;
				if(data.result){
					$scope.auditFrom.problemCode = data.result;
				}
				if(dataStatus == 3){
                    if(data.result)
                    {
                        Modal.alert(data.msg);
                        $scope.backAudit();
                    }else
                    {
                        Modal.alert("事件编号生成失败，请重新暂存或保存！");
                    }
				} else { // 暂存不关闭页面的情况下要刷新一下 机构,医保人员,参保人员信息
                    if(data.result)
                    {
                        Modal.alert(data.msg);
                        initDataLists(data.result);
                    }else
                    {
                        Modal.alert("事件编号生成失败，请重新暂存或保存！");
                    }
				}

			});
				 
		}
        $scope.markPoint=function(mark,data,code,orgType)
        {
            $scope.marking(mark,data,code,orgType);
        }

        //扣分 mark：1.机构扣分，2.医务人员扣分，3参保人员扣分,data:数据集合
        $scope.marking = function(mark,data,medicalCode,orgType){
            var medicalCodeTemp=null;
            if(medicalCode&&!angular.isUndefined(medicalCode)){
                medicalCodeTemp = medicalCode;
            }
            if(mark != 1 && medicalCodeTemp == null){
                Modal.alert("请先增加医疗机构信息！");
                return null;
            }else{
                medicalCode = medicalCodeTemp;
            }
            markData(mark,data,medicalCode,orgType);//扣分数据参数加载
            var modalInstance = $modal.open({
                templateUrl: baseUrl+'views/hcpms/warning/warnEdit/warningDeductionDialog_view.html',
                backdrop:'static',
                size:'sm',
                scope: $scope,
//					  scope:scope,
                controller: 'WarningDeductionDialogCtrl'
            });
            //接收返回数据
            modalInstance.result.then(function(item) {
                if (!WarningAddService.warningMarks) {
                    WarningAddService.warningMarks = [];
                }
                WarningAddService.warningMarks = item;
              //更新当前页面数据
     		   	WarningScreenService.findPointCutTempScose(
     		   		item,$stateParams.problemCode,'02',
     				  $scope.initMedicalData[0],$scope.initStaffData,$scope.initInsuranceData);
            });
        }
        //扣分数据参数加载
        var markData = function(mark,data,medicalCode,orgType){
            WarningAddService.mark = mark;
            WarningAddService.warningMarkData = {
                orgType:orgType,//0.机构，1.药店
                medicalCode:medicalCode,//medicalCode:所属机构编号
                code:data.selfCode,//code:编号
                name:data.name,//name:名称
                caseType:'02',//案件类型caseType：01.预警,02.稽核
                caseNo: $stateParams.problemCode,//事件编号
                happenDate: '',//受理日期
                punishDateStart: '',// 事件开始日期
                punishDateEnd: '',// 事件结束日期
                warningMarks:WarningAddService.warningMarks
            };
        }

		$scope.sourceList=[{codeNo:'01',codeName:'群众投诉'},
			                 {codeNo:'02',codeName:'网上筛查'},
			                 {codeNo:'03',codeName:'智能预警'}];
		
		$scope.tabs=[{label:'医疗机构',id:0,url:'views/hcpms/audit/problemRegister/caseAudit_add_medical_list.html'},
		             {label:'医护人员',id:1,url:'views/hcpms/audit/problemRegister/caseAudit_add_staff_list.html'},
		             {label:'参保人',id:2,url:'views/hcpms/audit/problemRegister/caseAudit_add_insurance_list.html'}];
		
		$scope.selectedTab = $scope.tabs[0];
		$scope.currentTabIndex = 0;
		
		$scope.tabClick = function(tab) {
			$scope.selectedTab = tab;
			$scope.currentTabIndex=tab.id;
		}
		
		$scope.requestParam = {
                page:"1",
                pageSize:"20"
            };
		
		//初始化请求参数
		var _params = function (pCode){
			var problemCode;
			if(pCode == null) {
				problemCode = $stateParams.problemCode;
			}else {
				problemCode = pCode;
			}
			var params = {
					problemNo:problemCode
			}
			return params;
		}
		
	  
		
	  /**
        * 调新增医疗机构的回调函数
        */
//      var medicalCode='';
       $scope.callMedicalFun=function(item){
    	   var medicalData = $scope.initMedicalData;
    	   if(item != null) {
    		   $scope.caseMedicalData = item;
    		   var total =  angular.isUndefined($scope.medicalCount)?0:$scope.medicalCount;
    		   if(angular.isUndefined(medicalData) || medicalData.length == 0){
    			   item.isDeleted = 0 ;
    			   item.flag = 1;
    			   $scope.initMedicalData.push(item);
    			   $scope.medicalCount = total++;
    		   }else{
    			   var lg = medicalData.length;
    			   var _t = 0;
    			   for(var j=0;j<lg;j++){
    				   var obj = medicalData[j];
    				   if(obj.medicalCode == item.medicalCode){
    					   _t = 1;
    					   if(obj.isDeleted == 1){
    						   obj.isDeleted = 0;   
    						   total++;
    					   }
    					   break;
    				   }
    			   }
    			   if(_t == 0 ){
    				   item.isDeleted = 0 ;
    				   item.flag = 1;
    				   $scope.initMedicalData.push(item);
    				   total++;
    			   }
    		   } 
    		   $scope.medicalCount = total;
    	   }
       }
	   
		
		// new add ----------------------
		$scope.addOrg = function(){
			CaseCommonService.addMedicalFun($scope);
		}
		
		$scope.deleteOrg = function(data){
			Modal.confirm("确认删除?",function(){
//				$scope.initMedicalData.splice(0,1);
//				$scope.medicalCount = 0;
				$scope.caseMedicalData = {};
				var _arr = $scope.initMedicalData;
				for(var i=0;i<_arr.length;i++){
					var obj = _arr[i];
					if(obj.medicalCode == data.medicalCode){
						WarningScreenService.deleteMark(WarningAddService.warningMarks,1,obj,$scope.initStaffData,$scope.initInsuranceData);
						$scope.medicalCount = 0;
						obj.isDeleted = 1;
						if(obj.flag == 1){
							$scope.initMedicalData.splice(i,1);
						}
						break;
					}
				}
			
			});
		}
		
		/**
		 * 调新增医务人员的回调函数
		 */
		$scope.callStaffFun=function(item){
			var  staffData = $scope.initStaffData ;
			 var total =  angular.isUndefined($scope.staffCount)?0:$scope.staffCount;
			 if(angular.isUndefined(staffData) || staffData.length == 0){
				 var tempArray = [];
				 for(var f=0;f<item.length;f++){
					 var obj = item[f];
					 obj.isDeleted = 0 ;
					 obj.flag = 1;
					 tempArray.push(obj);
					 total++;
				 }
				 $scope.initStaffData  = tempArray;
			 }else{
				 var lg = staffData.length;
				 for(var i=0;i<item.length;i++){
					 var obi = item[i];
					 var _t = 0;
					 for(var j=0;j<lg;j++){
						 var obj = staffData[j];
						 if(obj.staffCode == obi.staffCode){
							 _t = 1;
							 if(obj.isDeleted == 1){
								 obj.isDeleted = 0;
								 total++;
							 }
							 break;
						 }
					 }
					 if(_t == 0 ){
						 obi.isDeleted = 0 ;
						 obi.flag = 1;
						 $scope.initStaffData.push(obi);
						 total++;
					 }
				 }
			 } 
			 $scope.staffCount = total;
		 
		}
	       
		$scope.addStaff = function(){
			CaseCommonService.addStaffFun($scope);
		}
		
		$scope.deleteStaff = function(data){
			Modal.confirm("确认删除?",function(){
				WarningScreenService.deleteMark(WarningAddService.warningMarks,2,data);
				var _arr = $scope.initStaffData;
				for(var i=0;i<_arr.length;i++){
					var obj = _arr[i];
					if(obj.staffCode == data.staffCode){
						$scope.staffCount--;
						obj.isDeleted = 1;
						if(obj.flag == 1){
							$scope.initStaffData.splice(i,1);
						}
						break;
					}
				}
			});
		}
		
		$scope.addInsurance = function(){ 
			CaseCommonService.addInsuranceFun($scope);
		}
		
		/**
		 * 调新增参保人员的回调函数
		 */
		$scope.callInsuranceFun=function(item){
			var isData = $scope.initInsuranceData;
			var total =  angular.isUndefined($scope.insurCount)?0:$scope.insurCount;
			if(angular.isUndefined(isData) || isData.length == 0){
				var tempArray = [];
				for(var f=0;f<item.length;f++){
					var obj = item[f];
					obj.isDeleted = 0 ;
					obj.flag = 1;
					tempArray.push(obj);
					total++;
				}
				$scope.initInsuranceData  = tempArray;
			}else{
				var lg = isData.length;
				for(var i=0;i<item.length;i++){
					var obi = item[i];
					var _t = 0;
					for(var j=0;j<lg;j++){
						var obj = isData[j];
						if(obj.insuranceNo == obi.insuranceNo){
							_t = 1;
							if(obj.isDeleted == 1){
								obj.isDeleted = 0;
								total++;
							}
							break;
						}
					}
					if(_t == 0 ){
						obi.isDeleted = 0 ;
						obi.flag = 1;
						isData.push(obi);
						total++;
					}
				}
			} 
			$scope.insurCount = total;
		}

		$scope.deleteInsurance = function(data){
			Modal.confirm("确认删除?",function(){
				var _arr = $scope.initInsuranceData;
				for(var i=0;i<_arr.length;i++){
					var obj = _arr[i];
					if(obj.insuranceNo == data.insuranceNo){
						$scope.insurCount--;
						obj.isDeleted = 1;
						if(obj.flag == 1){
							$scope.initInsuranceData.splice(i,1);
						}
						break;
					}
				}
			});
		}
		
		//隐藏扣分以及删除按钮
		$scope.mouseoutShow = function(data){
			data.show = false;
		}
		
		//显示扣分以及删除按钮
		$scope.mouseoverShow = function(data){
			data.show = true;
		}

		$scope.viewInsurList = function(){
			CaseCommonService.viewInsurList($scope);
		}
		
		$scope.viewMedical = function(){
			CaseCommonService.viewMedicalDetail($scope);
		}
		
		
		$scope.viewStaffList = function(){
//			var _marks = WarningAddService.warningMarks;
//			if($scope.initStaffData!=null && $scope.initStaffData.length!=0){
//				if(_marks && _marks.length!=0){
//					var _maskData =_marks[0].deducitonStaffs;
//					for(var i=0;i<$scope.initStaffData.length;i++){
//						var mark = [];
//						for(var j =0;j<_maskData.length;j++){
//							if($scope.initStaffData[i].staffCode
//									== _maskData[j].targetNo){
//								mark.push(_maskData[j]);
//							}
//						}
//						$scope.initStaffData[i].markData = mark;
//					}
//				}
//			}
			CaseCommonService.viewStaffList($scope);
		}
		
		/**
		 * 初始化医疗机构数据和医护人员信息和参保人信息
		 */
		function initDataLists(pcode){
			var parameter=_params(pcode);
			CaseCommonService.loadMedicalInfoList(parameter).success(function(response){
				//if(!response)return;
				if(response.insuranceBean){
					$scope.initInsuranceData = response.insuranceBean.insuranceList;
					$scope.insurCount =response.insuranceBean.count; 
				}
				if(response.staffBean){
					$scope.initStaffData = response.staffBean.staffList;
					$scope.staffCount =response.staffBean.count;
				}
				if(response.medicalBean){
					$scope.initMedicalData = response.medicalBean.medicalList;
				}
				//更新当前页面数据
				WarningAddService.warningMarks = [];
				var _code = pcode!=null?pcode:$stateParams.problemCode;
     		   	var isTrue = WarningScreenService.findPointCutTempScose(
     				   WarningAddService.warningMarks,_code,'02',
     				  $scope.initMedicalData[0],$scope.initStaffData,$scope.initInsuranceData);
                if($scope.initMedicalData)
                {
                	$scope.caseMedicalData=$scope.initMedicalData[0];
                }
				$scope.medicalCount =response.medicalBean.count;
				//初始化 扣分查看页面
			});
		}
		
		if(!angular.isUndefined($stateParams.problemCode) && $stateParams.problemCode ){
			$scope.queryDetail($stateParams.problemCode);
			$scope.problemStatus=$stateParams.problemStatus;
			initDataLists(null);
		}

		
		// end script
	}]);
})();